import axios from 'axios';
import router from '@/router/index';
import { Message } from 'element-ui';

// create an axios instance
const service = axios.create({
    baseURL: "http://localhost:10010",
    timeout: 8000
})


//前置拦截，我们在这里统一将token设置到请求头中
service.interceptors.request.use(handle => {
    //seesionStorage中的数据当页面关闭就会消失
    const token = sessionStorage.getItem("token");
    handle.headers.Authorization = token;
    return handle;
}, error => {
    return Promise.reject(error);
})

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data

        if (res.code !== 200) {
           if(res.code === 6004) {
               router.push('/login');
           }
           Message({
            message: res.msg || 'Error',
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject("请求发生错误")
        } else {
            return res
        }
    }
)

export default service